<?php
declare(strict_types=1);

namespace Service\Consumer\YunCangConsumer\Router;
use Service\BaseService;
use App\Model\BbcModel\GoodsSupplyClass;
use App\Model\BbcModel\GoodsClass;
use Service\Code\Normal;

/**
 * 分类变更
 * @author chenshubo
 */
class classChange extends BaseService
{
    /**
     * 接收消费数据
     * @param int $sid
     * @param int $cid
     * @param array $data
     * @param string $messageId
     * @param int $IsFinished
     */
    public function consumer(int $sid,int $cid,array $data,string $messageId,int $IsFinished)
    {
        try {
        
            $before = $data['before'];
            $after  = $data['after'];
            
            if( $after['ClassificationLevel'] == 3 && !empty($after['ClassificationID']) ) 
            {
                $supplyClass=GoodsSupplyClass::instance()->info(['name'=>$before['ClassificationName'],'cid'=>$cid]);
                if ( $supplyClass )
                {
                    GoodsSupplyClass::instance()->where('id',$supplyClass['id'])->update([
                        'name'      => $after['ClassificationName'],
                        'supply_id' => $after['ClassificationID']
                    ]);
                }
                else
                {
                    $supplyClassData = [];
                    $supplyClassData['cid']         = $cid;
                    $supplyClassData['sid']         = $sid;
                    $supplyClassData['name']        = $after['ClassificationName'];
                    $supplyClassData['supply_id']   = $after['ClassificationID'];
                    $class= GoodsClass::instance()->info([
                        'name'  => $after['ClassificationName'],
                        'df'    => 0,
                        'cid'   => $cid
                    ]);
                    
                    if( $class ) {
                        $supplyClassData['class_id'] = $class['id'];
                    }
                    GoodsSupplyClass::instance()->add($supplyClassData);
                }
            }
            return Normal::returnCode(Normal::SUC,"处理完成");
        } catch ( \Throwable $th ) {
            $error = [
                'error'         => $th->getMessage(),
                'errorFile'     => $th->getFile(),
                'errorLine'     => $th->getLine(),
            ];
            $_class_name = __CLASS__;
            return Normal::returnCode(Normal::FAIL,"{$_class_name}消费处理处理异常【{$error['error']}】",$error);
        }
    }
}